import os
import uuid
from flask import Blueprint, request, jsonify, current_app, url_for
from werkzeug.utils import secure_filename
from flask_wtf.csrf import CSRFProtect

uploads_bp = Blueprint('uploads', __name__)
csrf = CSRFProtect()


def allowed_file(filename):
    """检查文件扩展名是否合法"""
    return '.' in filename and \
        filename.rsplit('.', 1)[1].lower() in {'png', 'jpg', 'jpeg', 'gif', 'webp'}


@uploads_bp.route('/upload_image', methods=['POST'])
@csrf.exempt
def upload_image():
    """处理图片上传"""
    if 'image' not in request.files:
        return jsonify({'success': False, 'message': 'No image selected'}), 400

    image = request.files['image']
    if not image or image.filename == '':
        return jsonify({'success': False, 'message': 'No image selected'}), 400

    try:
        if not allowed_file(image.filename):
            return jsonify({'success': False, 'message': 'Unsupported file type'}), 400

        upload_dir = os.path.join(current_app.root_path, 'static', 'uploads')
        os.makedirs(upload_dir, exist_ok=True)

        filename = secure_filename(image.filename)
        if not filename:
            return jsonify({'success': False, 'message': 'Invalid filename'}), 400

        unique_name = f"{uuid.uuid4().hex}_{filename}"
        save_path = os.path.join(upload_dir, unique_name)

        if request.content_length > 5 * 1024 * 1024:
            return jsonify({'success': False, 'message': 'File too large (max 5MB)'}), 400

        image.save(save_path)

        image_url = url_for('static', filename=f'uploads/{unique_name}', _external=False)
        return jsonify({
            'success': True,
            'url': image_url,
            'alt': os.path.splitext(filename)[0]
        })

    except Exception as e:
        current_app.logger.error(f'Image upload failed: {str(e)}')
        return jsonify({'success': False, 'message': 'Upload failed'}), 500
